import {
  login,
  getCode
} from '../../api/sso';
import {
  setLoginInfo
} from '../../utils/auth';

const app = getApp();

Component({
  // 在组件的 properties 中添加
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    forceLogin: {  // 添加强制登录属性
      type: Boolean,
      value: false
    }
  },

  data: {
    isPhoneLogin: false,
    phone: '',
    code: '',
    countdown: 0,
    openid: '',
    binding: false
  },

  methods: {
    // 关闭弹窗
    onClose() {
      // 如果设置了强制登录且用户未登录，则不允许关闭
      if (this.data.forceLogin) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        // 触发需要强制登录的事件，让页面处理
        this.triggerEvent('forceLoginClose');
        return;
      }
      
      this.setData({
        show: false
      });
      this.triggerEvent('close');
    },

    // 切换到手机号登录
    switchToPhone() {
      this.setData({
        isPhoneLogin: true
      });
    },

    // 微信一键登录
    async handleWechatLogin() {
      try {
        wx.showLoading({
          title: '登录中...'
        });

        const loginRes = await wx.login();
        if (!loginRes.code) {
          throw new Error('微信登录失败');
        }

        const res = await login({
          type: 'weChatAuthService',
          code: loginRes.code
        });

        // 保存登录信息
        if (res.data.openId) {
          // 如果返回了openId，说明是首次登录或未绑定手机号
          this.setData({
            openid: res.data.openId,
            binding: true,
            isPhoneLogin: true // 自动切换到手机号登录界面
          });
          wx.hideLoading();

          wx.showToast({
            title: '请绑定手机号',
            icon: 'none'
          });
        } else {
          // 正常登录成功
          const userInfo = await setLoginInfo(res.data);
          wx.hideLoading();
          this.onClose();
          this.triggerEvent('getUserInfoSuccess', userInfo);
        }
      } catch (err) {
        wx.hideLoading();
        wx.showToast({
          title: err.message || '登录失败',
          icon: 'none'
        });
      }
    },

    // 手机号登录/绑定
    async handlePhoneLogin() {
      const {
        phone,
        code,
        openid
      } = this.data;
      if (!phone || !code) {
        wx.showToast({
          title: '请输入手机号和验证码',
          icon: 'none'
        });
        return;
      }

      try {
        wx.showLoading({
          title: '登录中...'
        });

        const params = {
          type: 'verificationCodeAuthService',
          phone,
          code
        };

        if (this.data.binding && openid) {
          params.openid = openid;
        }

        const res = await login(params);
        const userInfo = await setLoginInfo(res.data);
        // 先设置到全局store
        app.store.setUserInfo(userInfo);
        wx.hideLoading();
        
        // 登录成功后，无论是否设置了强制登录，都关闭模态框
        this.setData({
          show: false
        });
        
        this.triggerEvent('getUserInfoSuccess', userInfo);

        if (openid) {
          wx.showToast({
            title: '绑定成功',
            icon: 'success'
          });
        }
      } catch (err) {
        wx.hideLoading();
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      }
    },

    // 切换回选择登录方式
    switchToSelect() {
      this.setData({
        isPhoneLogin: false,
        phone: '',
        code: '',
        countdown: 0
      });
    },

    // 获取验证码
    async getVerifyCode() {
      const {
        phone,
        countdown
      } = this.data;

      if (countdown > 0) return;

      if (!/^1[3-9]\d{9}$/.test(phone)) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }

      try {
        wx.showLoading({
          title: '发送中...'
        });
        await getCode({
          phone
        });
        wx.hideLoading();

        this.setData({
          countdown: 60
        });
        this.startCountdown();

        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
      } catch (err) {
        wx.hideLoading();
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      }
    },

    // 倒计时
    startCountdown() {
      const timer = setInterval(() => {
        const {
          countdown
        } = this.data;
        if (countdown <= 1) {
          clearInterval(timer);
          this.setData({
            countdown: 0
          });
        } else {
          this.setData({
            countdown: countdown - 1
          });
        }
      }, 1000);
    }
  }
});